package com.wufun.overseas.main.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JavaType;
import com.wufun.baselibrary.net.HttpUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.models.bean.UpdateBean;
import com.wufun.overseas.rpc.RpcConstant;
import com.wufun.overseas.utils.JsonMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by tangbl on 2017/12/10 0010.
 */

public class MoreSettingActivity extends MyActivity {

    @Bind(R.id.papaVer)
    TextView papaVer;

    UpdateBean bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_setting);
        ButterKnife.bind(this);
    }

    public static Intent buildIntent(Context context, String title) {
        Intent intent = new Intent(context, MoreSettingActivity.class);
        intent.putExtra("title", title);
        return intent;
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);
        setBarTitleTx(getIntent().getStringExtra("title"));
    }

    @OnClick({R.id.shareLayout, R.id.checkVerLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shareLayout:

                break;
            case R.id.checkVerLayout:
                getUpdateInformation();
                break;
        }
    }

    private void getUpdateInformation() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("type", getResources().getString(R.string.Home_Title).replace(" ", ""));
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            String code = pi.versionCode + "";

            HttpUtils.doGet(RpcConstant.forumRootUrl + "/forum/checkupdate?type="
                    + getResources().getString(R.string.app_flag).replace(" ", "") + "&version=" + code, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    Log.e("getUpdateInformation:", "onFailure");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    if (str != null) {
                        bean = new UpdateBean();
                        JavaType javaType = JsonMapper.getInstance().createCollectionType(UpdateBean.class);
                        bean = JsonMapper.getInstance().fromJson(str, javaType);
                        Log.e("TAG", bean.toString());
                        if (bean.getData().getCode().equals("200")) {
                            getDiaLog();
                        } else if (bean.getData().getCode().equals("300")) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Toast.makeText(MoreSettingActivity.this, "It's the latest version", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void getDiaLog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(MoreSettingActivity.this);
                builder.setTitle("Update tip");
                builder.setMessage("Whether to update ?");
                builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                                   dialog.dismiss();
                    }
                });
                builder.setPositiveButton("update", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String str = bean.getData().getLink();
                        String head = str.substring(0, str.indexOf(":"));
                        if (head.indexOf("https") != -1 || head.indexOf("http") != -1) {
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri uri = Uri.parse(bean.getData().getLink());
                            intent.setData(uri);
                            startActivity(intent);
                        }


                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }
}
